package com.max.socket.client;

import com.alibaba.fastjson.JSON;
import com.max.socket.dto.MsgDTO;
import com.max.socket.dto.MsgType;
import com.max.view.ChatWindow;

import java.io.*;
import java.net.Socket;
import java.util.function.Consumer;

public class ChatSocketClientThread extends Thread {

    private final String ip;
    private final int port;
    private final String username;

    private Consumer<MsgDTO> sendMsgToWindow;


    public ChatSocketClientThread(String ip, int port, String username) {
        this.ip = ip;
        this.port = port;
        this.username = username;
    }

    @Override
    public void run() {
        try (Socket socket = new Socket(ip, port)) {
            OutputStream os = socket.getOutputStream();
            InputStream is = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            PrintWriter writer = new PrintWriter(os, true);

            while (true) {
                String msg = reader.readLine();
                MsgDTO msgDTO = JSON.parseObject(msg, MsgDTO.class);
                System.out.println("client-收到消息：" + msg);
                switch (msgDTO.getMsgType()) {
                    case GET_NAME -> {
                        MsgDTO sendMsg = new MsgDTO(MsgType.SEND_NAME, username, username);
                        writer.println(JSON.toJSONString(sendMsg));
                    }
                    case ACCEPT -> {
                        System.out.println("新用户：" + msgDTO.getContent() + "加入聊天室");
                        //commandLine(writer);
                        new ChatWindow(writer, username, e -> sendMsgToWindow = e);
                    }
                    case MSG -> {
//                        System.out.println(msgDTO.getSender() + ":" + msgDTO.getContent());
                        if(sendMsgToWindow != null){
                            sendMsgToWindow.accept(msgDTO);
                        }
                    }
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


   /* public static void commandLine(PrintWriter writer) {
        new Thread(() -> {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
                while (true) {
                    String msg = reader.readLine();
                    MsgDTO msgDTO = new MsgDTO(MsgType.MSG, msg, "max");
                    //把消息发送出去
                    //System.out.println(JSON.toJSONString(msgDTO));
                    writer.println(JSON.toJSONString(msgDTO));
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }
*/
}
